package com.weblog.user.utils;

import com.weblog.model.user.Permission;
import com.weblog.model.user.Role;
import com.weblog.user.dao.RoleDao;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;

/**
 * @author MaoLin Wang
 * @date 2019/9/2019:31
 */
public class AccessUtil {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private RoleDao roleDao;

    /**
     * 是否拥有操作权限
     * @param targetRole  目标角色
     * @param targetPermission 目标权限
     * @return
     */
    public int isAccess(String targetRole, String targetPermission) {
        List<String> roles = (List<String>) request.getAttribute("roles");
        System.out.println("roles111111111111"+roles.size());
        String target_Role = "";
        for (String r : roles) {
            if (targetRole.equals(r)) {
                //拥有targetRole角色
                target_Role = r;
            }
        }
        if ("".equals(target_Role)) {
            //没有目标角色
            return 2;//权限不足
        }
        boolean has_access = false;

        Role admin_role = roleDao.findRoleByRname(targetRole);//得到目标角色实体
        Set<Permission> permissions = admin_role.getPermissions();//目标角色的权限集合
        if(permissions==null||permissions.size()<1){
            return 2;
        }
        for (Permission p : permissions) {
            if (targetPermission.equals(p.getPname())) {
                //拥有目标权限
                has_access = true;
            }
        }
        if (!has_access) {
            return 2;
        }


        return 1;
    }



}
